package com.hy.demo.learn.thread.竞拍抢答;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * <p>
 * 多线程竞拍抢答实例demo
 * </p>
 *
 * @author cjl
 * @version 1.0
 * @since 2020-08-27 10:54
 */
public class ThreadDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread myThread = new MyThread();
        FutureTask<String> futureTask1 = new FutureTask<String>(myThread);
        FutureTask<String> futureTask2 = new FutureTask<String>(myThread);
        FutureTask<String> futureTask3 = new FutureTask<String>(myThread);
        new Thread(futureTask1, "竞拍--A").start();
        new Thread(futureTask2, "竞拍--B").start();
        new Thread(futureTask3, "竞拍--C").start();
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
        System.out.println(futureTask3.get());

    }

}

class MyThread implements Callable<String> {

    // 抢答标识
    private boolean flag = false;

    @Override
    public String call() throws Exception {

        synchronized (this) {
            if (!this.flag) {
                flag = true;
                return Thread.currentThread().getName() + "抢答成功";
            } else {
                return Thread.currentThread().getName() + "抢答失败";
            }
        }
    }
}